package ru.bytedog.oiot.counter.bot.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.telegram.telegrambots.bots.TelegramLongPollingBot;
import org.telegram.telegrambots.meta.api.methods.send.SendMessage;
import org.telegram.telegrambots.meta.api.methods.updatingmessages.DeleteMessage;
import org.telegram.telegrambots.meta.api.objects.Update;
import org.telegram.telegrambots.meta.exceptions.TelegramApiException;
import ru.bytedog.oiot.counter.bot.bean.BotAnswer;
import ru.bytedog.oiot.counter.bot.service.command.CommandProcessor;

@Slf4j
@Component
public class TelegramBot extends TelegramLongPollingBot {

    private final CommandProcessor processor;
    private final String botName;

    public TelegramBot(@Value("${telegram.botToken}") String botToken, @Value("${telegram.botName}") String botName, CommandProcessor processor) {
        super(botToken);
        this.processor = processor;
        this.botName = botName;
    }

    @Override
    public void onUpdateReceived(Update update) {
        if (!update.hasMessage() || !update.getMessage().hasText()) {
            return;
        }
        sendMessage(processor.processMessage(update.getMessage()));
    }

    @Override
    public String getBotUsername() {
        return botName;
    }


    public void sendMessage(BotAnswer answer) {
        try {
            if (answer.getDeleteMessageId() != null) {
                execute(new DeleteMessage(answer.getChatId(), answer.getDeleteMessageId()));
            }
            execute(new SendMessage(answer.getChatId(), answer.getMessage()));
        } catch (TelegramApiException e) {
            log.error("Ошибка отправки сообщения", e);
        }
    }
}
